<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('account.accountInfo')"
    custom-class="dialog-min-width"
    :width="500"
    :destroy-on-close="true"
    @close="onClose"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-alert
            :title="t('account.passwordWarning')"
            type="warning"
            :closable="false"
          /><br />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="margin-bottom: 10px">
          <el-form-item :label="t('account.oldPassword')" prop="oldPassword">
            <el-input
              v-model="formEdit.oldPassword"
              :type="type0"
              @focus="type0 = 'password'"
              show-password
              minlength="8"
              maxlength="20"
              autocomplete="new-password"
              clearable
              @onkeypress="capsLockOn($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="margin-bottom: 10px">
          <el-form-item :label="t('account.newPassword')" prop="newPassword">
            <el-input
              v-model="formEdit.newPassword"
              :type="type1"
              @focus="type1 = 'password'"
              show-password
              minlength="8"
              maxlength="20"
              autocomplete="new-password"
              clearable
              @onkeypress="capsLockOn($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            :label="t('account.confirmPassword')"
            prop="confirmPassword"
            :class="store.appLocale == 'en_US' ? 'break-label' : ''"
          >
            <el-input
              v-model="formEdit.confirmPassword"
              :type="type2"
              @focus="type2 = 'password'"
              show-password
              minlength="8"
              maxlength="20"
              autocomplete="new-password"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from "vue";
import utils from "../../utils/utils";
import { useStore } from "../../stores/store";
import moment from "moment";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
import apiUser from "./api/user";
import apiAccount from "../admin/api/account";

const { proxy } = getCurrentInstance() as any;
const store = useStore();
const formRef = ref();
const publicKey = ref("");
const loading = ref(false);
const type0 = ref("");
const type1 = ref("");
const type2 = ref("");

const emit = defineEmits<{
  (event: "on-submit-success", lastChangePasswordTime: string): void;
  (event: "on-close", passwordChanged: boolean): void;
}>();

const formEditOriginal = () =>
  reactive({
    sessionId: "",
    accountId: "",
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
const formEdit = reactive(formEditOriginal());

const capsLockOn = (event) => {
  "大写锁定已打开";
};

const rules = ref({
  oldPassword: [
    { required: true, message: t("common.required"), trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: t("common.required"), trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (formEdit.newPassword === "") {
          callback(new Error(t("common.required")));
        } else if (!utils.validatePassword(formEdit.newPassword)) {
          callback(new Error(t("account.passwordWarning")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: t("common.required"), trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (formEdit.newPassword !== value) {
          callback(new Error(t("account.passwordInconsistent")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const state = reactive({
  dialogFormVisible: false,
  passwordChanged: false,
});

const onClose = () => {
  emit("on-close", state.passwordChanged);
};

const handleSubmit = async () => {
  await formRef.value.validate();

  // 加密数据，清理原文
  let encryptedOldPassword = utils.doSm2Encrypt(
    publicKey.value,
    formEdit.oldPassword
  );
  let encryptedNewPassword = utils.doSm2Encrypt(
    publicKey.value,
    formEdit.newPassword
  );
  // 加密数据，清理原文
  // 处理业务逻辑，触发关闭事件
  loading.value = true;
  apiUser
    .changeAccountPassword(
      formEdit.sessionId,
      encryptedOldPassword,
      encryptedNewPassword
    )
    .then((response: any) => {
      loading.value = false;
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        state.passwordChanged = true;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", moment().format("YYYY-MM-DD HH:mm:ss"));
      }
    })
    .catch((err: any) => {
      // 还原原文
      loading.value = false;
      utils.errorNotification(t("common.submitException"), err);
    });
  //   updateUserPwd(formEdit.oldPassword, formEdit.newPassword).then((response) => {
  //     proxy.$modal.msgSuccess("修改成功");
  //     state.dialogFormVisible = false;
  //   });
};

const getPublicKey = () => {
  formEdit.sessionId = utils.getUUID();
  apiAccount
    .generateSessionPublicKeyQ(formEdit.sessionId)
    .then((response: any) => {
      if (response.data.code == 200) {
        publicKey.value = response.data.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = () => {
  Object.assign(formEdit, formEditOriginal());
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
  getPublicKey();
  loading.value = false;
  state.dialogFormVisible = true;
};

defineExpose({
  show,
});
</script>
